/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.delivery;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.util.ArrayMap;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.coupon.DeductionLogicKeeper;
import cn.com.dhc.danlu.activity.coupon.UseDealersEnvelopActivity;
import cn.com.dhc.danlu.activity.coupon.model.GoodsCoupon;
import cn.com.dhc.danlu.activity.envelope.EnvelopDeductionPresenter;
import cn.com.dhc.danlu.activity.envelope.EnvelopeableActivity;
import cn.com.dhc.danlu.business.shopcar.bean.WrapDealerAttr;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.dlware.net.func.RetryWhenNetworkException;
import cn.com.dhc.danlu.fragment.ValidationEnvelopFragment;
import cn.com.dhc.danlu.fragment.ValidationEnvelopFragment.ICommitListener;
import cn.com.dhc.danlu.model.AccountPaymentType;
import cn.com.dhc.danlu.model.CreateOrderCashOnDeliveryModels;
import cn.com.dhc.danlu.model.ShoppingCartCommitModel;
import cn.com.dhc.danlu.util.CalculatePriceUtil;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.EmojiFilter;
import cn.com.dhc.danlu.util.GsonFactory;
import cn.com.dhc.danlu.util.PatternConstants;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.GradationScrollView;
import cn.com.dhc.danlu.widget.adapter.OrderShopAdapter;
import cn.com.dhc.danlu.widget.dialog.PromotionDetailDialog;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.danlu.widget.holder.OrderConfirmCalHolder;
import cn.com.dhc.danlu.widget.holder.OrderConfirmStoreHolder;
import cn.com.dhc.danlu.widget.home.HomeListView;
import cn.com.hd.mall.web.webservices.entity.freedom.entity.coupon.CouponEntity;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.GetCouponCntWithDealerReq;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.GetCouponWithMerchReq;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.GetCouponCntWithDealerResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.GetCouponWithMerchResponse;
import cn.com.hd.mall.web.webservices.entity.request.envelop.GetCouponListRequest;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.CreateOrderRequest;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.CreateOrderRequest.CouponListBean;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.CreateOrderRequest.DeliverAddressBean;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.CreateOrderRequest.InvoiceBean;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.CreateOrderRequest.SellerListBean.MerchListBean.DealerBenefitBean;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.DealerMinDeliveryAmtRequest;
import cn.com.hd.mall.web.webservices.entity.response.common.GetCouponParamResponse;
import cn.com.hd.mall.web.webservices.entity.response.cpx.GetCouponListResponse;
import cn.com.hd.mall.web.webservices.entity.response.cpx.GetCouponListResponse.CouponListModel;
import cn.com.hd.mall.web.webservices.entity.response.mydl.deliveraddr.DeliverAddressListReponse.DeliverAddressListModel;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.CheckSwitchResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.CreateOrderByShoppingcartNewResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.CreateOrderResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.CreateOrderResponse.CreateOrderInfoModelBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.DealerMinDeliveryAmtResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.OnChangedPromotionInfoResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean.PromotionModelListBean;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CalculatePriceUtil.addition;

/**
 * author: MuWei
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-19 16:32<br/>
 * <p>
 * 订单确认画面(“提交订单”页面）
 * </p>
 */
public class OrderConfirmActivity extends BaseActivity implements OnClickListener {
    public static final int USE_ENVELOP_REQ = 0x1110;

    /**
     * 上次选择的发票模型
     */
    private final InvoiceBean lastRecord = new InvoiceBean();
    /**
     * 经销商ID - >订单中该经销商下所有商品总额(扣除满减满赠后) 单位：分
     */
    private final HashMap<String, String> totalGoodsAmoutMap = new HashMap<>();
    /**
     * 店铺UI元素对象列表
     */
    private final List<OrderConfirmStoreHolder> storeHolderList = new ArrayList<>();
    /**
     * 品类优化
     */
    private final ArrayMap<WrapDealerAttr, BigDecimal> dealersTotalGoodsAmountMap = new ArrayMap<>();
    boolean isLoadEnvelopSuc = false;
    /**
     * 收货人地址
     */
    private LinearLayout llyUserAddress;
    /**
     * 收货人
     */
    private TextView recevieUser;
    /**
     * 收货人电话
     */
    private TextView userTel;
    /**
     * 收货人地址
     */
    private TextView userAddress;
    /**
     * 发票信息
     */
    private LinearLayout llytInvoiceMsg;
    /**
     * 发票信息
     */
    private TextView invoiceCompany;
    private GradationScrollView svScrollview;
    /**
     * 页面跳转
     */
    private Intent intent = new Intent();
    /**
     * 容器
     */
    private LinearLayout llytchildContainer;
    /**
     * 支付方式页面
     */
    private LinearLayout llytPayment;
    /**
     * 提交布局
     */
    private TextView tvOrder;
    /**
     * 默认普通发票id
     */
    private int invoiceID = 2;
    /**
     * 合计 Text
     */
    private TextView tvTotalPrice;
    /**
     * 支付方式txt
     */
    private TextView payWay;
    private ViewGroup rootView;
    /**
     * 购物车结算数据模型
     */
    private ShoppingCartCommitModel shoppingCartCommitModel = null;
    /**
     * 选中的地址模型
     */
    private DeliverAddressBean selectedAddressModel = null;
    /**
     * 选择的发票模型
     */
    private InvoiceBean selectedInvoiceModel = null;
    private String lastInvoiceName;
    /**
     * 选择的支付方式
     */
    private String paywayValue = CommonConst.PaymentType.PAY_TYPE_ON_LINE;
    /**
     * 上一次 选择的支付方式记忆
     */
    private String lastPayWayValue = paywayValue;
    private String vatInvoiceSupport = "0";
    /**
     * 收货地址ID
     */
    private String defaultAddressId = "";
    /**
     * 存储商品ID与已选促销模型之间的映射
     */
    private HashMap<String, OnChangedPromotionInfoResponse> goodsPromotionModelMap = new HashMap<>();
    /**
     * 存储商品ID与已选促销一览模型之间的映射
     */
    private HashMap<String, PromotionModelListBean> goodsPromotionMap = new HashMap<>();
    /**
     * 支付类型对象
     */
    private AccountPaymentType accountPaymentType = null;
    /**
     * 我的红包管理
     */
    private RelativeLayout rlGetenvelop;
    private ProgressBar pbLoadding;
    private TextView tvEnvelopCount;
    private String envelopListJsonStr;
    private ArrayList<CouponListModel> selectEnvelops = new ArrayList<>();
    private float payRatio;
    private OrderConfirmCalHolder calcHolder;
    /**
     * 红包优惠 折叠视图presenter
     */
    private EnvelopDeductionPresenter envelopDeductionPresenter;
    /**
     * 标识当前是否是零元订单
     */
    private boolean isZeroOrder = false;
    private ValidationEnvelopFragment validationEnvelopFragment;
    private DeductionLogicKeeper deductionLogicKeeper;
    // 丹露红包消费
    private TextView tvEnvelopDanluUseAmount;
    // 底部悬浮地址栏
    private TextView tvBottomAddress;
    private LinearLayout llBottomAdd;
    private View viewAddressLine;
    private TextView tvImmPayTips;

    private int thresholdScrollValue = 0;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_confirm);

        calcHolder = new OrderConfirmCalHolder(getWindow().getDecorView());
        deductionLogicKeeper = new DeductionLogicKeeper(this);

        initView();
        initData();
        setViews();
        setListener();
        // 请求webservice 去获取最新优惠券列表（可用+不可用）
        fetchCouponList();

    }

    private void initView() {
        llyUserAddress = (LinearLayout) findViewById(R.id.llyUserAddress);
        recevieUser = (TextView) findViewById(R.id.recevie_user);
        userTel = (TextView) findViewById(R.id.user_tel);
        userAddress = (TextView) findViewById(R.id.user_address);
        llytInvoiceMsg = (LinearLayout) findViewById(R.id.llytInvoiceMsg);
        invoiceCompany = (TextView) findViewById(R.id.invoice_company);
        svScrollview = (GradationScrollView) findViewById(R.id.sv_scrollview);
        llytchildContainer = (LinearLayout) findViewById(R.id.ll_order_info_container);
        llytPayment = (LinearLayout) findViewById(R.id.llytPayment);
        tvOrder = (TextView) findViewById(R.id.tvOrder);
        tvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        payWay = (TextView) findViewById(R.id.payWay);
        rootView = (ViewGroup) findViewById(R.id.root_view);
        rlGetenvelop = (RelativeLayout) findViewById(R.id.rl_getenvelop);
        pbLoadding = (ProgressBar) findViewById(R.id.pb_loadding);
        tvEnvelopCount = (TextView) findViewById(R.id.tv_envelop_count);
        tvEnvelopDanluUseAmount = (TextView) findViewById(R.id.tvEnvelopDanluUseAmount);
        tvBottomAddress = (TextView) findViewById(R.id.tvBottomAddress);
        llBottomAdd = (LinearLayout) findViewById(R.id.llBottomAdd);
        viewAddressLine = findViewById(R.id.viewAddressLine);
        tvImmPayTips = (TextView) findViewById(R.id.tv_imm_pay_tips);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    @Override
    protected void back() {
        this.finish();
    }

    private void setListener() {
        findViewById(R.id.llytBack).setOnClickListener(this);
        llyUserAddress.setOnClickListener(this);
        llytInvoiceMsg.setOnClickListener(this);
        llytPayment.setOnClickListener(this);
        tvOrder.setOnClickListener(this);
        rlGetenvelop.setOnClickListener(this);
        svScrollview.setScrollViewListener(new GradationScrollView.ScrollViewListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
                if (thresholdScrollValue > 0) {
                    int scrollValue = Math.abs(y);
                    if (scrollValue > thresholdScrollValue) {
                        llBottomAdd.setVisibility(View.VISIBLE);
                    } else {
                        llBottomAdd.setVisibility(View.GONE);
                    }
                }
            }
        });
        viewAddressLine.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                viewAddressLine.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                thresholdScrollValue = viewAddressLine.getTop(); //view自身相对与父控件的高度
            }
        });
    }

    /**
     * 初始化数据模型
     */
    @SuppressWarnings("unchecked")
    private void initData() {
        // 获取购物车传递的结算数据模型
        String modelJson = getIntent().getStringExtra(CommonConst.IntentKey.SHOPPING_CART_COMMIT_MODEL);
        shoppingCartCommitModel = GsonFactory.getGson().fromJson(modelJson, ShoppingCartCommitModel.class);
        // 默认选择普通发票
        intent.putExtra(CommonConst.IntentKey.INVOICE_ID, invoiceID);
        // 获取促销
        // 存放diffprice
        goodsPromotionModelMap = (HashMap<String, OnChangedPromotionInfoResponse>) getIntent().getSerializableExtra(CommonConst.IntentKey.CART_COMMIT_PROMOTION_VALUE_MODEL);
        // 存放促销文案
        goodsPromotionMap = (HashMap<String, PromotionModelListBean>) getIntent().getSerializableExtra(CommonConst.IntentKey.CART_COMMIT_PROMOTION_MODEL);
        calcHolder.refreshOriginPrice(getIntent().getStringExtra("origintotalprice"));// 刷新原价
        //默认情况下是不开发票的
        lastRecord.setNeedInvoice(CommonConst.InvoiceConst.NEED_INVOICE_NO);
    }

    /**
     * 初始化视图
     */
    private void setViews() {
        llBottomAdd = (LinearLayout) findViewById(R.id.llBottomAdd);
        // 地址信息赋值
        if (shoppingCartCommitModel != null && shoppingCartCommitModel.getToSettlementInfoModel() != null && shoppingCartCommitModel.getToSettlementInfoModel().getDeliverAddress() != null) {
            DeliverAddressListModel addressModel = shoppingCartCommitModel.getToSettlementInfoModel().getDeliverAddress();
            recevieUser.setVisibility(View.VISIBLE);
            userTel.setVisibility(View.VISIBLE);
            userAddress.setVisibility(View.VISIBLE);
            defaultAddressId = shoppingCartCommitModel.getToSettlementInfoModel().getDeliverAddress().getAddressId();
            refreshAddressUI(addressModel);
            saveAddressRequest(addressModel);
        } else {
            defaultAddressId = "";
            recevieUser.setVisibility(View.GONE);
            userTel.setVisibility(View.GONE);
            userAddress.setVisibility(View.GONE);
        }
        // 发票信息赋值
        if (shoppingCartCommitModel != null && shoppingCartCommitModel.getToSettlementInfoModel() != null && shoppingCartCommitModel.getToSettlementInfoModel().getDefaultNormalInvoice() != null) {
            invoiceCompany.setText(getString(R.string.order_confirm_select_invoice_tip));
            selectedInvoiceModel = null;
        } else {
            invoiceCompany.setText(getString(R.string.order_confirm_select_invoice_tip));
        }
        // 记录
        lastInvoiceName = invoiceCompany.getText().toString().trim();
        // 支付方式赋值
        accountPaymentType = getPaymentType();
        if (accountPaymentType.isSupportCodForAllSeller()) { // 默认货到付款
            payWay.setText(getString(R.string.pay_arrive));
            paywayValue = CommonConst.PaymentType.PAY_TYPE_COD;
            tvImmPayTips.setVisibility(View.GONE);
        } else if (accountPaymentType.getSupportCodCount() > 0 && accountPaymentType.getOnLinePaymentCount() > 0) { // 默认货到+在线
            payWay.setText(getString(R.string.pay_online_arrive));
            paywayValue = CommonConst.PaymentType.PAY_TYPE_ALL;
            tvImmPayTips.setVisibility(View.VISIBLE);
        } else if (accountPaymentType.isOnlinePayForAllSeller()) { // 默认在线支付
            payWay.setText(getString(R.string.pay_online));
            paywayValue = CommonConst.PaymentType.PAY_TYPE_ON_LINE;
            tvImmPayTips.setVisibility(View.VISIBLE);
        }
        lastPayWayValue = paywayValue;

        // 添加店铺及商品列表
        if (shoppingCartCommitModel != null && shoppingCartCommitModel.getSellerList() != null) {
            buildStoreListView();
            // 数据绑定
            bindStoreData();
        }

    }

    /**
     * 添加店铺列表
     */
    private void buildStoreListView() {
        ArrayList<String> dealerIds = new ArrayList<>();
        // 店铺数据列表
        List<SellerListBean> sellerList = shoppingCartCommitModel.getSellerList();
        for (int i = 0; i < sellerList.size(); i++) {
            // why add
            final String dealerId = sellerList.get(i).getSellerId();
            final String splitDealerId = dealerId.substring(0, dealerId.indexOf("_"));
            dealerIds.add(splitDealerId);
            @SuppressLint("InflateParams")
            View viewStore = LayoutInflater.from(this).inflate(R.layout.item_order_confirm, null);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, CommonUtils.dipToPx(OrderConfirmActivity.this, 10), 0, 0);
            viewStore.setLayoutParams(lp);
            llytchildContainer.addView(viewStore);
            OrderConfirmStoreHolder storeHolder = new OrderConfirmStoreHolder();
            storeHolder.etBuyerMsg = (EditText) viewStore.findViewById(R.id.et_buyer_msg);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                storeHolder.etBuyerMsg.setHintTextColor(getColor(R.color.color_cdcbcb));
            } else {
                storeHolder.etBuyerMsg.setHintTextColor(getResources().getColor(R.color.color_cdcbcb));
            }
            storeHolder.etBuyerMsg.setFilters(new InputFilter[]{new EmojiFilter()});
            storeHolder.ivCod = (ImageView) viewStore.findViewById(R.id.iv_cod);
            storeHolder.ivVat = (ImageView) viewStore.findViewById(R.id.iv_vat);
            storeHolder.hlvOrders = (HomeListView) viewStore.findViewById(R.id.hlv_orders);
            storeHolder.tvStoreName = (TextView) viewStore.findViewById(R.id.tv_store_name);
            storeHolder.llDealerEnvelop = (LinearLayout) viewStore.findViewById(R.id.ll_dealer_envelop);
            storeHolder.tvDealerEnvelopDed = (TextView) viewStore.findViewById(R.id.tv_dealer_envelop_amount);
            storeHolder.tvDealerEnvelopCount = (TextView) viewStore.findViewById(R.id.tv_dealer_envelop_count);
            storeHolder.tvGift = (TextView) viewStore.findViewById(R.id.tv_gift);
            storeHolder.tvReduce = (TextView) viewStore.findViewById(R.id.tv_reduce);
            storeHolder.llReduce = (LinearLayout) viewStore.findViewById(R.id.ll_reduce);
            storeHolder.llPromotion = (LinearLayout) viewStore.findViewById(R.id.ll_promotion);
            storeHolder.llDealerEnvelop.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    deductionLogicKeeper.gotoDealerEnvelop(splitDealerId);
                }
            });
            storeHolder.dealerId = splitDealerId;
            storeHolderList.add(storeHolder);
        }
        // 请求获取每一个经销商最大支付比
        deductionLogicKeeper.setDealerIds(dealerIds);
    }

    /***
     * 绑定店铺数据
     */
    @SuppressLint("SetTextI18n")
    private void bindStoreData() {
        if (storeHolderList == null || storeHolderList.size() < 1) {
            return;
        }

        // 店铺数据列表
        List<SellerListBean> sellerList = shoppingCartCommitModel.getSellerList();
        if (storeHolderList.size() != sellerList.size()) {
            return;
        }

        // 促销 - 满减总
        BigDecimal substractTotal = new BigDecimal(0);
        // 促销 - 满减单
        BigDecimal substractSingle = new BigDecimal(0);
        // 促销 - 促销减价
        BigDecimal substractLimit = new BigDecimal(0);

        // 所有商品集合  用于批量查询商品优惠券
        ArrayList<String> merchIds = new ArrayList<>();
        for (int i = 0; i < storeHolderList.size(); i++) {
            final OrderConfirmStoreHolder storeHolder = storeHolderList.get(i);
            final SellerListBean storeModel = sellerList.get(i);
            if (CommonConst.ShoppingCarModel.IS_SUPPLY_COD_PAYMENT_0.equals(storeModel.getSupportCod())) {
                // 支持货到付款
                storeHolder.ivCod.setVisibility(View.VISIBLE);
            } else {
                storeHolder.ivCod.setVisibility(View.GONE);
            }

            if (CommonConst.ShoppingCarModel.IS_SUPPLY_INVOICE_0.equals(storeModel.getSupportVatInvoice())) {
                // 支持增值税发票
                storeHolder.ivVat.setVisibility(View.VISIBLE);
            } else {
                // 不支持增值税发票
                storeHolder.ivVat.setVisibility(View.GONE);
                vatInvoiceSupport = "1";
            }

            // 商品列表
            OrderShopAdapter adapter = new OrderShopAdapter(OrderConfirmActivity.this, storeModel.getMerchList(), goodsPromotionModelMap, goodsPromotionMap);
            storeHolder.hlvOrders.refreshView(adapter);
            // 店铺名称
            storeHolder.tvStoreName.setText(storeModel.getSellerName());

            // 起售金额
            String[] categorySellerId = storeModel.getSellerId().split("_split_");
            WrapDealerAttr attr = new WrapDealerAttr(categorySellerId[0], storeModel.getSellerName());

            // why add
            ArrayList<GoodsCoupon> goodsCoupons = new ArrayList<>();
            List<MerchListBean> storeMerchList = storeModel.getMerchList();
            BigDecimal bdTotalGoodsAmout = new BigDecimal(0);

            for (int j = 0; j < storeMerchList.size(); j++) {
                MerchListBean goodsModel = storeMerchList.get(j);
                GoodsCoupon goodsCoupon = new GoodsCoupon();
                goodsCoupon.setMerchId(goodsModel.getMerchId());
                goodsCoupon.setMerchQuantity(goodsModel.getMerchQuantity());
                goodsCoupon.setUnitPrice(goodsModel.getUnitPrice());
                goodsCoupon.setPriceDanlu(goodsModel.getPriceDanlu());
                goodsCoupon.setPriceRetail(goodsModel.getPriceRetail());
                // 添加用于批量查询
                merchIds.add(goodsModel.getMerchId());

                if (goodsPromotionMap.get(goodsModel.getMerchId()) != null) {
                    // 说明指定index = j商品存在促销
                    PromotionModelListBean promotionResponse = goodsPromotionMap.get(goodsModel.getMerchId());
                    if (promotionResponse != null && (!TextUtils.isEmpty(promotionResponse.getDiffPrice()) || !TextUtils.isEmpty(promotionResponse.getPresentationDetail()))) {
                        // why add
                        PromotionModelListBean promotionModel = new PromotionModelListBean();
                        String merchId = goodsModel.getMerchId();
                        String reductionType = goodsPromotionMap.get(merchId).getReductionType();
                        String promotionType = goodsPromotionMap.get(merchId).getPromotionType();
                        // 获取商品数量
                        BigDecimal goodCount = new BigDecimal(goodsModel.getMerchQuantity());

                        // why add
                        promotionModel.setPromotionType(promotionType);
                        promotionModel.setReductionType(reductionType);
                        promotionModel.setDiffPrice(goodsPromotionMap.get(merchId).getDiffPrice());
                        goodsCoupon.setPromotionModel(promotionModel);

                        // 满减
                        if (promotionType.equals(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1)) {
                            BigDecimal diffPrice = new BigDecimal(goodsPromotionMap.get(merchId).getDiffPrice());
                            // 计算到底是满减单还是满减总 的总价
                            if (reductionType.equals(CommonConst.PromotionConst.REDUCTION_TYPE_1)) {
                                // 满减总
                                substractTotal = substractTotal.add(diffPrice);
                            } else if (reductionType.equals(CommonConst.PromotionConst.REDUCTION_TYPE_0)) {
                                // 满减单价
                                substractSingle = substractSingle.add(diffPrice.multiply(goodCount));
                            }
                        } else if (promotionType.equals(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4)) {
                            // 限购
                            // TODO: 2017/3/20 限购价格 @lyf #ok
                            BigDecimal limitLeftTimes = new BigDecimal(goodsPromotionModelMap.get(merchId).getLimitTimesLeft());
                            BigDecimal merchUnitPrice = new BigDecimal(goodsModel.getUnitPrice());
                            BigDecimal limitPrice = new BigDecimal(goodsPromotionMap.get(merchId).getLimitRuleList().get(0).getLimitPrice());

                            if (limitLeftTimes.compareTo(goodCount) >= 0) {
                                substractLimit = substractLimit.add(merchUnitPrice.subtract(limitPrice).multiply(goodCount));
                            } else {
                                substractLimit = substractLimit.add(merchUnitPrice.subtract(limitPrice).multiply(limitLeftTimes));
                            }
                        }
                    }
                }
                // 计算商品促销优惠后（不管优惠券使用情况）的总价
                bdTotalGoodsAmout = addition(bdTotalGoodsAmout.toPlainString(), deductionLogicKeeper.getGoodsTotalAmount(goodsCoupon).toPlainString());
                goodsCoupons.add(goodsCoupon);
            }
            // 起售金额
            dealersTotalGoodsAmountMap.put(attr, bdTotalGoodsAmout);

            String sellerId = storeModel.getSellerId();
            String dealerId = sellerId.substring(0, sellerId.indexOf("_"));
            totalGoodsAmoutMap.put(dealerId, bdTotalGoodsAmout.toPlainString());
            //why add  还未添加商品优惠券信息
            deductionLogicKeeper.putDealerGoodsList(dealerId, goodsCoupons);

            // 字数监听
            storeHolder.etBuyerMsg.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int editTextCLength = 0;
                    int editTextELength = 0;
                    String str = s.toString().trim();
                    for (int i = 0; i < str.length(); i++) {
                        if ((i + 1) <= str.length()) {
                            String ss = str.substring(i, i + 1);
                            if (CommonUtils.patternMatchFind(ss, PatternConstants.PATTERN_CONTAIN_CHINESE)) {
                                editTextCLength = editTextCLength + 2;
                                int a = editTextCLength + editTextELength;

                                if (a > 1000) {
                                    storeHolder.etBuyerMsg.setText(str.substring(0, i));
                                    storeHolder.etBuyerMsg.setSelection(i);
                                    return;
                                }
                            } else {
                                editTextELength = editTextELength + 1;
                                int a = editTextCLength + editTextELength;

                                if (a > 1000) {
                                    storeHolder.etBuyerMsg.setText(str.substring(0, i));
                                    storeHolder.etBuyerMsg.setSelection(i);
                                    return;
                                }
                            }
                        }
                    }
                }
            });

            // 限购 add lyf 2017年03月20日15:26:24
            if (storeModel.getPromotionBean().isValid()) {
                if (TextUtils.isEmpty(storeModel.getPromotionBean().getMsgGift())) {
                    storeHolder.tvGift.setVisibility(View.GONE);
                } else {
                    storeHolder.tvGift.setVisibility(View.VISIBLE);
                    storeHolder.tvGift.setText("促销赠送：" + storeModel.getPromotionBean().getMsgGift());
                }

                if (TextUtils.isEmpty(storeModel.getPromotionBean().getMsgReduce())) {
                    storeHolder.llReduce.setVisibility(View.GONE);
                } else {
                    storeHolder.llReduce.setVisibility(View.VISIBLE);
                    storeHolder.tvReduce.setText(storeModel.getPromotionBean().getMsgReduce());
                }

                if (storeHolder.tvGift.getVisibility() == View.GONE && storeHolder.llReduce.getVisibility() == View.GONE) {
                    storeHolder.llPromotion.setVisibility(View.GONE);
                } else {
                    storeHolder.llPromotion.setVisibility(View.VISIBLE);
                    storeHolder.llPromotion.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // TODO: 2017/3/20 显示促销信息弹窗 add lyf #ok
                            PromotionDetailDialog detailDialog = new PromotionDetailDialog(OrderConfirmActivity.this);
                            detailDialog.refreshContent(storeModel.getPromotionBean());
                            detailDialog.show();
                        }
                    });
                }
            } else {
                storeHolder.llPromotion.setVisibility(View.GONE);
            }
        }

        // 计算完成 开始刷新计算区域 优惠总价
        BigDecimal total = substractSingle.add(substractTotal).add(substractLimit);
        calcHolder.refreshPreferential(total.toPlainString());

        // why 获取所有商品优惠券 获取完成之后将要刷新每一个经销商下的商品优惠券默认选择项 同时更新DeductionLogicKeeper 中经销商下所买商品所选择的优惠券
        getEveryGoodsCoupons(merchIds);  //有加载动画
        // 获取所有经销商可用红包数量
        getAllDealersEnvelopCnt(); //无加载动画

        reCalculateTotal();
        svScrollview.postDelayed(new Runnable() {
            @Override
            public void run() {
                svScrollview.scrollTo(0, 0);
            }
        }, 200);
    }

    /**
     * 获取所有经销商红包可用红包数量
     */
    private void getAllDealersEnvelopCnt() {
        Iterator<Map.Entry<String, String>> iterator = totalGoodsAmoutMap.entrySet().iterator();
        List<GetCouponCntWithDealerReq.DealerParamEntity> list = new ArrayList<>();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();
            GetCouponCntWithDealerReq.DealerParamEntity ent = new GetCouponCntWithDealerReq.DealerParamEntity();
            ent.setDealerId(key);
            ent.setTotalAmt(CalculatePriceUtil.intercept(value)); //去掉小数可能性
            list.add(ent);
        }
        agent.getApi()
                .getCouponCntWithDealer(new GetCouponCntWithDealerReq(agent.getToken(), list))
                .compose(OperatorUtils.<GetCouponCntWithDealerResponse> defaultSchedulers())
                .retryWhen(new RetryWhenNetworkException())
                .subscribe(new GeneralBusinessObserver<GetCouponCntWithDealerResponse>() {
                    @Override
                    protected void onSuccess(GetCouponCntWithDealerResponse model) {
                        refreshDealerEnvelopCntView(model);
                    }
                });
    }

    /**
     * 刷新经销商可用红包数量
     */
    @SuppressLint("SetTextI18n")
    private void refreshDealerEnvelopCntView(GetCouponCntWithDealerResponse model) {
        List<GetCouponCntWithDealerResponse.UnUsedCntListEntity> usedCntList = model.getUnUsedCntList();
        if (null == usedCntList || usedCntList.isEmpty()) {
            return;
        }
        for (OrderConfirmStoreHolder holder : storeHolderList) {
            String sellerIdTag = holder.dealerId;
            for (GetCouponCntWithDealerResponse.UnUsedCntListEntity entity : usedCntList) {
                if (entity.getDealerId().equals(sellerIdTag)) {
                    String unUsedCnt = entity.getUnUsedCnt();
                    BigDecimal bdCnt = new BigDecimal(unUsedCnt);
                    int compare = CalculatePriceUtil.compare(bdCnt.toPlainString(), "0");
                    if (compare == 0) {
                        holder.tvDealerEnvelopCount.setText("无可用");
                    } else {
                        holder.tvDealerEnvelopCount.setText(unUsedCnt + "个可用");
                    }
                }
            }
        }
    }

    /**
     * 批量查询商品优惠券信息
     */
    private void getEveryGoodsCoupons(ArrayList<String> merchIds) {
        if (merchIds.isEmpty()) {
            return;
        }
        agent.getApi()
                .getCouponWithMerch(new GetCouponWithMerchReq(agent.getToken(), merchIds))
                .compose(OperatorUtils.<GetCouponWithMerchResponse> defaultSchedulers())
                .retryWhen(new RetryWhenNetworkException())
                .subscribe(new GeneralBusinessObserver<GetCouponWithMerchResponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(GetCouponWithMerchResponse model) {
                        refreshGoodsCoupon(model.getCouponModelList());
                    }
                });
    }

    private void refreshGoodsCoupon(List<GetCouponWithMerchResponse.CouponModelListEntity> couponModelList) {
        if (null == couponModelList || couponModelList.isEmpty()) {
            return;
        }
        for (final OrderConfirmStoreHolder holder : storeHolderList) {
            HomeListView goodsListView = holder.hlvOrders;
            String dealerId = holder.dealerId;
            for (int i = 0; i < goodsListView.getChildCount(); i++) {
                View convertView = goodsListView.getChildAt(i);
                View view = convertView.findViewById(R.id.ll_goods_coupon);
                if (null != view && null != view.getTag()) {
                    String goodsId = (String) view.getTag();
                    for (final GetCouponWithMerchResponse.CouponModelListEntity goodsCoupon : couponModelList) {
                        if (goodsCoupon.getMerchId().equals(goodsId) && goodsCoupon.getFlag().equals("true")) {
                            boolean canUseCoupon = judgePriceGreaterThanLimit(dealerId, goodsId, goodsCoupon.getCoupon().getAmtLimit());
                            if (canUseCoupon) {
                                view.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        showGoodsCouponPopupwindow(v, holder.dealerId, goodsCoupon);
                                    }
                                });
                                view.setTag(R.id.coupon_goods_tag_key, true);
                                // 选择一个默认商品优惠券
                                GetCouponWithMerchResponse.CouponModelListEntity.CouponEntity coupon = goodsCoupon.getCoupon();
                                // 刷新itemView 界面
                                TextView tvGoodsCoupon = (TextView) view.findViewById(R.id.tv_goods_coupon);
                                tvGoodsCoupon.setText(buildCouponTips(coupon.getAmtLimit(), coupon.getCouponAmt()));
                                // 刷新keeperlogic
                                DealerBenefitBean dealerBenefitEntity = new DealerBenefitBean();
                                dealerBenefitEntity.setCouponAmt(coupon.getCouponAmt());
                                dealerBenefitEntity.setCouponCode(coupon.getCouponCode());
                                deductionLogicKeeper.changeDealerGoodsBenefits(holder.dealerId, goodsId, dealerBenefitEntity);
                                // 清除丹露红包
                                selectEnvelops.clear();
                                //  刷新
                                switchGoodsChainReaction(holder.dealerId);
                                view.setVisibility(View.VISIBLE);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    private boolean judgePriceGreaterThanLimit(String dealerId, String goodsId, String limit) {
        GoodsCoupon coupon = deductionLogicKeeper.getGoodsModelById(dealerId, goodsId);
        if (null != coupon) {
            BigDecimal amount = deductionLogicKeeper.getGoodsTotalAmount(coupon);
            int compare = CalculatePriceUtil.compare(amount.toPlainString(), limit);
            return compare == 0 || compare == 1;
        }
        return false;
    }

    /**
     * 获取最新优惠券列表
     */
    private void fetchCouponList() {
        // 改变UI 状态
        tvEnvelopCount.setVisibility(View.GONE);
        pbLoadding.setVisibility(View.VISIBLE);
        GetCouponListRequest request = new GetCouponListRequest();
        List<String> merchIdList = new ArrayList<>();
        for (SellerListBean model : shoppingCartCommitModel.getSellerList()) {
            for (MerchListBean goods : model.getMerchList()) {
                merchIdList.add(goods.getMerchId());
            }
        }
        request.setToken(agent.getToken());
        request.setMerchList(merchIdList);
        request.setCompanyId(agent.getLoginUser().getCompanyId());
        agent.getApi()
                .getCouponList(request)
                .compose(OperatorUtils.<GetCouponListResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetCouponListResponse>() {
                    @Override
                    protected void onSuccess(GetCouponListResponse model) {
                        isLoadEnvelopSuc = true;
                        envelopListJsonStr = CommonUtils.parseBean2Json(model);
                        int size = 0;
                        if (model.getUseablecouponList() != null) {
                            size = model.getUseablecouponList().size();
                        }
                        tvEnvelopCount.setVisibility(View.VISIBLE);
                        pbLoadding.setVisibility(View.GONE);
                        if (size > 0) {
                            tvEnvelopCount.setText("可用" + size + "个");
                        } else {
                            tvEnvelopCount.setText("暂无可用红包");
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        isLoadEnvelopSuc = false;
                        pbLoadding.setVisibility(View.GONE);
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 切换商品优惠券 连锁反应
     */
    private void switchGoodsChainReaction(String dealerId) {
        refreshDlEnvelopLinkage();

        refreshDealerEnvelopDedById(dealerId);
        refreshGoodsConponDed();
        //  刷新合计 & 提交订单总价
        reCalculateTotal();
    }

    private void refreshGoodsConponDed() {
        BigDecimal deduction = deductionLogicKeeper.getTotalCouponDeduction();
        calcHolder.refreshGoodsCouponDed(deduction.toPlainString());
    }

    private String buildCouponTips(String amtLimit, String couponAmt) {
        BigDecimal couponBd = CommonUtils.fenToYuan(new BigDecimal(couponAmt));
        String s = CalculatePriceUtil.converseAmount(couponBd.toPlainString());
        String limitStr = "";
        if (!TextUtils.isEmpty(amtLimit) && CalculatePriceUtil.compare(amtLimit, String.valueOf(0)) != 0) {
            BigDecimal limitBd = CommonUtils.fenToYuan(new BigDecimal(amtLimit));
            limitStr = "满" + CalculatePriceUtil.converseAmount(limitBd.toPlainString()) + "元";
        }
        return "优惠券：" + limitStr + "减" + s + "元";
    }

    /**
     * 显示选择是否使用经销商优惠券的界面
     */
    private void showGoodsCouponPopupwindow(final View item, final String dealerId, final GetCouponWithMerchResponse.CouponModelListEntity goodsCoupon) {
        final GetCouponWithMerchResponse.CouponModelListEntity.CouponEntity coupon = goodsCoupon.getCoupon();
        Object tag = item.getTag(R.id.coupon_goods_tag_key);
        boolean isCheckUse = true;
        if (null != tag) {
            isCheckUse = (boolean) tag;
        }
        final String buildCouponTips = buildCouponTips(coupon.getAmtLimit(), coupon.getCouponAmt());
        OrderDealerEnvelopPopView popupView = new OrderDealerEnvelopPopView(this, rootView, buildCouponTips);
        popupView.setSelectState(isCheckUse, !isCheckUse);
        popupView.setOnChooseListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DealerBenefitBean couponEntity = null;
                TextView tvGoodDes = (TextView) item.findViewById(R.id.tv_goods_coupon);
                if (v.getId() == R.id.rl_use) {
                    couponEntity = new DealerBenefitBean();
                    couponEntity.setCouponCode(coupon.getCouponCode());
                    couponEntity.setCouponAmt(coupon.getCouponAmt());
                    item.setTag(R.id.coupon_goods_tag_key, true);
                    tvGoodDes.setText(buildCouponTips);
                } else {
                    item.setTag(R.id.coupon_goods_tag_key, false);
                    tvGoodDes.setText("不使用优惠券");
                }
                deductionLogicKeeper.changeDealerGoodsBenefits(dealerId, goodsCoupon.getMerchId(), couponEntity);
                selectEnvelops.clear();
                switchGoodsChainReaction(dealerId);
            }
        });
        popupView.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 获取可选支付方式计算对象
     */
    private AccountPaymentType getPaymentType() {
        // 店铺数据列表
        List<SellerListBean> sellerList = shoppingCartCommitModel.getSellerList();
        if (sellerList == null || sellerList.size() < 1) {
            return null;
        }

        AccountPaymentType accountPaymentType = new AccountPaymentType(sellerList.size());
        for (SellerListBean storeModel : sellerList) {
            if (CommonConst.ShoppingCarModel.IS_SUPPLY_COD_PAYMENT_0.equals(storeModel.getSupportCod())) {
                accountPaymentType.addSupportCodCount(1);
            }
            if (CommonConst.ShoppingCarModel.IS_SUPPLY_YJF_PAYMENT_0.equals(storeModel.getIsYijipayAccount())) {
                accountPaymentType.addOnLinePaymentCount(1);
            }
        }
        return accountPaymentType;
    }

    protected void showFragmentTips(String string) {
        if (null != validationEnvelopFragment) {
            validationEnvelopFragment.setTip(string);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommonConst.OrderConfirmConst.INVOICE_REQUEST_CODE && resultCode == RESULT_OK) {
            selectedInvoiceModel = new InvoiceBean();
            // 获取选择的发票
            invoiceID = data.getIntExtra(CommonConst.IntentKey.INVOICE_ID, 0);

            if (invoiceID == CommonConst.InvoiceConst.ID_NO_INVOICE) {
                // 不选发票
                intent.putExtra(CommonConst.IntentKey.INVOICE_ID, invoiceID);
                // 设置默认支付方式txt
                selectedInvoiceModel.setNeedInvoice(CommonConst.InvoiceConst.NEED_INVOICE_NO);
                selectedInvoiceModel.setInvoiceType(null);
                selectedInvoiceModel.setInvoiceId(null);
                invoiceCompany.setText(getResources().getString(R.string.no_invoice));
            } else if (invoiceID == CommonConst.InvoiceConst.ID_NORMAL_INVOICE) {
                // 普通发票
                intent.putExtra(CommonConst.IntentKey.INVOICE_ID, invoiceID);
                String invoiceName = data.getStringExtra(CommonConst.IntentKey.INVOICE_NAME);

                // 设置默认支付方式txt
                if (!TextUtils.isEmpty(invoiceName)) {
                    invoiceCompany.setText(invoiceName);
                    selectedInvoiceModel.setNeedInvoice(CommonConst.InvoiceConst.NEED_INVOICE_YES);
                    selectedInvoiceModel.setInvoiceType("N011");
                    selectedInvoiceModel.setInvoiceId(data.getStringExtra("invoiceId"));
                    intent.putExtra("invoiceId", data.getStringExtra("invoiceId"));
                    selectedInvoiceModel.setInvoiceHeader(invoiceName);
                } else {
                    intent.putExtra(CommonConst.IntentKey.INVOICE_ID, 1);
                    selectedInvoiceModel.setNeedInvoice(CommonConst.InvoiceConst.NEED_INVOICE_NO);
                    selectedInvoiceModel.setInvoiceType(null);
                    selectedInvoiceModel.setInvoiceId(null);
                    invoiceCompany.setText(getResources().getString(R.string.no_invoice));
                }
            } else if (invoiceID == CommonConst.InvoiceConst.ID_ADD_INVOICE) {
                // 增值税发票
                intent.putExtra(CommonConst.IntentKey.INVOICE_ID, invoiceID);
                String invoiceName = data.getStringExtra(CommonConst.IntentKey.INVOICE_NAME);
                // 设置默认支付方式txt
                invoiceCompany.setText(invoiceName);
                selectedInvoiceModel.setNeedInvoice(CommonConst.InvoiceConst.NEED_INVOICE_YES);
                selectedInvoiceModel.setInvoiceType("N012");
                selectedInvoiceModel.setInvoiceId(data.getStringExtra(CommonConst.IntentKey.INVOICE_NAME));
            }

            lastInvoiceName = invoiceCompany.getText().toString().trim();
            lastRecord.setNeedInvoice(selectedInvoiceModel.getNeedInvoice());
            lastRecord.setInvoiceType(selectedInvoiceModel.getInvoiceType());
            lastRecord.setInvoiceId(selectedInvoiceModel.getInvoiceId());
            lastRecord.setInvoiceHeader(selectedInvoiceModel.getInvoiceHeader());
        } else if (requestCode == CommonConst.OrderConfirmConst.PAYMENT_REQUEST_CODE && resultCode == RESULT_OK) {
            // 获取支付方式显示txt,默认在线支付
            int payWayId = data.getIntExtra(CommonConst.IntentKey.PAY_ID, 0);
            if (payWayId == CommonConst.InvoiceConst.ONLINE) {// 在线支付
                payWay.setText(getResources().getString(R.string.pay_online));
                paywayValue = CommonConst.PaymentType.PAY_TYPE_ON_LINE;
                tvImmPayTips.setVisibility(View.VISIBLE);
            } else if (payWayId == CommonConst.InvoiceConst.ONLINE_ARRIVE) {// 在线+货到
                payWay.setText(getResources().getString(R.string.pay_online) + "+" + getResources().getString(R.string.pay_arrive));
                paywayValue = CommonConst.PaymentType.PAY_TYPE_ALL;
                tvImmPayTips.setVisibility(View.VISIBLE);
            } else if (payWayId == CommonConst.InvoiceConst.ARRIVE) {// 货到
                payWay.setText(getResources().getString(R.string.pay_arrive));
                paywayValue = CommonConst.PaymentType.PAY_TYPE_COD;
                tvImmPayTips.setVisibility(View.GONE);
            } else if (payWayId == CommonConst.InvoiceConst.COMPANY) {// 公司转账
                payWay.setText(getResources().getString(R.string.pay_company_change));
            }
            lastPayWayValue = paywayValue;
        } else if (requestCode == CommonConst.OrderConfirmConst.ADDRESS_REQUEST_CODE && resultCode == RESULT_OK) {
            String strModel = data.getStringExtra(CommonConst.IntentKey.ADDRESS_MODEL);

            if (strModel != null) {
                DeliverAddressListModel addressModel = GsonFactory.getGson().fromJson(strModel, DeliverAddressListModel.class);
                shoppingCartCommitModel.getToSettlementInfoModel().setDeliverAddress(addressModel);
                refreshAddressUI(addressModel);
                saveAddressRequest(addressModel);
                defaultAddressId = addressModel.getAddressId();
            }
        } else if (requestCode == USE_ENVELOP_REQ && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            // 当前用户选中的红包
            selectEnvelops = (ArrayList<CouponListModel>) bundle.getSerializable("select");
            refreshDlEnvelopLinkage();
            //  刷新合计 & 提交订单总价
            reCalculateTotal();
        } else if (requestCode == UseDealersEnvelopActivity.USE_DEALER_ENVELOP_REQ && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String selectJsonStr = bundle.getString("selectJsonStr");
            List<CouponEntity> list = null;
            try {
                list = CommonUtils.fromJsonArray(selectJsonStr, CouponEntity.class);
                deductionLogicKeeper.onUseDealerEnvelopResult(bundle.getString("dealerId"), list);
                refreshDealerEnvelopDedById(bundle.getString("dealerId")); //刷新
                selectEnvelops.clear();
                refreshDlEnvelopLinkage();
                //  刷新合计 & 提交订单总价
                reCalculateTotal();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 地址UI赋值
     */
    @SuppressLint("SetTextI18n")
    private void refreshAddressUI(DeliverAddressListModel addressModel) {
        recevieUser.setVisibility(View.VISIBLE);
        userTel.setVisibility(View.VISIBLE);
        userAddress.setVisibility(View.VISIBLE);
        recevieUser.setText(addressModel.getDeliverPerson());
        userTel.setText(addressModel.getDeliverMobile());
        String address = addressModel.getAreaProvinceName() + addressModel.getAreaCityName() + addressModel.getAreaDistrictName() + addressModel.getAddressDetail();
        userAddress.setText(address);
        tvBottomAddress.setText(address);
    }

    /**
     * 保存地址选择对象
     */
    private void saveAddressRequest(DeliverAddressListModel addressModel) {
        selectedAddressModel = new DeliverAddressBean();
        selectedAddressModel.setDeliverAddress(addressModel.getAreaProvinceName() + addressModel.getAreaCityName() + addressModel.getAreaDistrictName() + addressModel.getAddressDetail());
        selectedAddressModel.setDeliverMobile(addressModel.getDeliverMobile());
        selectedAddressModel.setDeliverPerson(addressModel.getDeliverPerson());
    }

    /**
     * 重新计算丹露红包实际抵扣 并刷新 相关视图
     */
    @SuppressLint("SetTextI18n")
    private void refreshDlEnvelopLinkage() {
        refreshDanluEnvelopView(); //  刷新红包折叠视图
        BigDecimal deduction = envelopDeductionPresenter.getTotalDeduction();
        BigDecimal bigDecimal = CommonUtils.fenToYuan(deduction);
        //丹露红包item抵扣
        tvEnvelopDanluUseAmount.setText("- ¥ " + CommonUtils.formateRate(bigDecimal.toPlainString()));
        calcHolder.refreshDanluEnvelopDeduction(deduction.toPlainString()); //刷新底部丹露红包抵扣
    }

    private void reCalculateTotal() {
        // 先判断是不是零元订单
        BigDecimal afterDiscountPrice = calcHolder.getAfterDiscountPrice();
        int compare = CalculatePriceUtil.compare(afterDiscountPrice.toPlainString(), "0");

        if (compare == 1) {
            //不是零元订单
            isZeroOrder = false;
        } else {
            isZeroOrder = true;
            // 防止负数情况出现
            afterDiscountPrice = new BigDecimal(0);
        }
        BigDecimal afterBd = CommonUtils.fenToYuan(afterDiscountPrice);
        tvTotalPrice.setText(CommonUtils.formateRate(afterBd.toPlainString()));
        handleZeroBusiness(); // 零元订单相关处理
    }

    /**
     * 刷新指定经销商红包实际抵扣
     */
    @SuppressLint("SetTextI18n")
    private void refreshDealerEnvelopDedById(String dealerId) {
        for (OrderConfirmStoreHolder holder : storeHolderList) {
            if (dealerId.equals(holder.dealerId)) {
                BigDecimal envelopFactUseBd = deductionLogicKeeper.getDealerEnvelopFactUseById(dealerId);
                String s = CommonUtils.formateRate(CommonUtils.fenToYuan(envelopFactUseBd).toPlainString());
                holder.tvDealerEnvelopDed.setText("- ¥ " + s);
                //刷新底部经销商所有抵扣
                calcHolder.refreshDealerTotalEnvDed(deductionLogicKeeper.getTotalDealersEnvelopDeduction().toPlainString());
                break;
            }
        }
    }

    private void refreshDanluEnvelopView() {
        if (envelopDeductionPresenter == null) {
            envelopDeductionPresenter = new EnvelopDeductionPresenter();
        }
        envelopDeductionPresenter.refreshEnvelops(selectEnvelops);
    }

    /**
     * 零元订单相关处理
     */
    private void handleZeroBusiness() {
        // 底部零元订单提示
        calcHolder.isZeroOrder(isZeroOrder);
        if (isZeroOrder) {
            //显示tips:
            //不可发票 || 在线支付
            llytPayment.setEnabled(false);
            llytInvoiceMsg.setEnabled(false);
            invoiceCompany.setText(getResources().getString(R.string.no_invoice));
            payWay.setText(getResources().getString(R.string.pay_online));
            tvImmPayTips.setVisibility(View.VISIBLE);
            //设置请求参数为不可以开发票
            if (null == selectedInvoiceModel) {
                selectedInvoiceModel = new InvoiceBean();
            }

            selectedInvoiceModel.setNeedInvoice(CommonConst.InvoiceConst.NEED_INVOICE_NO);
            selectedInvoiceModel.setInvoiceType(null);
            selectedInvoiceModel.setInvoiceId(null);
            //设置支付方式为在线支付
            paywayValue = CommonConst.PaymentType.PAY_TYPE_ON_LINE;
        } else {
            llytPayment.setEnabled(true);
            llytInvoiceMsg.setEnabled(true);
            invoiceCompany.setText(lastInvoiceName);

            switch (lastPayWayValue) {
                case CommonConst.PaymentType.PAY_TYPE_ALL:
                    //在线支付+货到付款
                    payWay.setText(getResources().getString(R.string.pay_online_arrive));
                    tvImmPayTips.setVisibility(View.VISIBLE);
                    break;
                case CommonConst.PaymentType.PAY_TYPE_COD:
                    //货到付款方式
                    payWay.setText(getResources().getString(R.string.pay_arrive));
                    tvImmPayTips.setVisibility(View.GONE);
                    break;
                case CommonConst.PaymentType.PAY_TYPE_ON_LINE:
                    //在线支付
                    payWay.setText(getResources().getString(R.string.pay_online));
                    tvImmPayTips.setVisibility(View.VISIBLE);
                    break;
            }

            //请求参数
            paywayValue = lastPayWayValue;
            //设置请求参数为不可以开发票
            if (null == selectedInvoiceModel) {
                selectedInvoiceModel = new InvoiceBean();
            }
            selectedInvoiceModel.setNeedInvoice(lastRecord.getNeedInvoice());
            selectedInvoiceModel.setInvoiceType(lastRecord.getInvoiceType());
            selectedInvoiceModel.setInvoiceId(lastRecord.getInvoiceId());
            selectedInvoiceModel.setInvoiceHeader(lastRecord.getInvoiceHeader());
        }

    }

    /**
     * 商品信息发生改变
     */
    private void orderErrorMsg(CreateOrderResponse.FailedReasonsBean failedReasons) {
        if (failedReasons == null) {
            Toast.makeText(this, getResources().getString(R.string.commit_error_goods_tip), Toast.LENGTH_SHORT).show();
            return;
        }
        StringBuilder sbErrorInfo = new StringBuilder();
        // 商品被删除提示
        //        buildCommitErrorMsg (sbErrorInfo, failedReasons.getDelList (), R.string.commit_error_goods_deleted);
        // 商品无效提示
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getInvalidList(), R.string.commit_error_goods_invalid);
        // 商品名改变提示
        //        buildCommitErrorMsg (sbErrorInfo, failedReasons.getNameChangedList (), R.string.commit_error_goods_name_changed);
        // 商品缺货提示
        //        buildCommitErrorMsg (sbErrorInfo, failedReasons.getNoInventoryList (), R.string.commit_error_goods_no_inventory);
        // 商品库存不足提示
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getNoOnHandInventoryList(), R.string.commit_error_goods_no_onhandinventory);
        // 卖家增值税发票权限变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getNoSupplyInvoicList(), R.string.commit_error_goods_no_supplyinvoic);
        // 商品价格发生变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getPriceChangedList(), R.string.commit_error_goods_price_changed);
        // 商品已下架
        //        buildCommitErrorMsg (sbErrorInfo, failedReasons.getShelvesOffList (), R.string.commit_error_goods_shelves_off);
        // 商品规格变化
        //        buildCommitErrorMsg (sbErrorInfo, failedReasons.getSpecChangedList (), R.string.commit_error_goods_spec_changed);
        // 促销活动已失效
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getGoodsPromotionValidateFailList(), R.string.commit_error_goods_promotion_invalid);
        // 支付方式发生变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getSupplyCodPaymentChangedList(), R.string.commit_error_goods_supply_codpayment_changed);

        // 起售数量发生变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getLessThanMiniStartSaleQuantityList(), R.string.cart_reachMiniStartSaleQuantity_tips);
        //配送商红包支付比发生变化，请重新购买
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getDealerPayRatioChangedList(), R.string.envelop_payratio_changed);
        // 配送商起送金额发生变化，请重新购买
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getDealerMinDeliveryAmtChangedList(), R.string.dealer_minamount_changed);

        if (!TextUtils.isEmpty(failedReasons.getCouponErrorMessage())) {
            sbErrorInfo.append(failedReasons.getCouponErrorMessage());
        }

        if (sbErrorInfo.length() < 1) {
            ToastUtil.getInstance().show(R.string.commit_error_goods_tip);
            return;
        }

        intent.putExtra("ERRORMSG", sbErrorInfo.toString());
        intent.setClass(OrderConfirmActivity.this, OrderReferFailedActivity.class);
        startActivity(intent);
        OrderConfirmActivity.this.finish();
    }

    /**
     * 构建购物车结算失败提示信息
     */
    private void buildCommitErrorMsg(StringBuilder sb, List<String> itemList, int resStrId) {
        if (itemList != null && itemList.size() > 0) {
            for (String item : itemList) {
                sb.append(item);
                sb.append("\n");
            }
            sb.append(getString(resStrId));
            sb.append("\n");
        }
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.llytBack:
                finish();
                break;

            // 收货地址
            case R.id.llyUserAddress:
                intent.putExtra(CommonConst.IntentKey.ADDRESS_ID, defaultAddressId);
                intent.setClass(OrderConfirmActivity.this, UserAddressActivity.class);
                startActivityForResult(intent, CommonConst.OrderConfirmConst.ADDRESS_REQUEST_CODE);
                break;

            // 发票信息
            case R.id.llytInvoiceMsg:
                intent.putExtra("VATSUPPT", vatInvoiceSupport);
                intent.setClass(OrderConfirmActivity.this, InvoiceMainActivity.class);
                startActivityForResult(intent, CommonConst.OrderConfirmConst.INVOICE_REQUEST_CODE);
                break;

            // 支付方式
            case R.id.llytPayment:
                intent.putExtra("accountPaymentType", accountPaymentType);
                intent.putExtra("paymentChecked", payWay.getText().toString());
                intent.setClass(OrderConfirmActivity.this, OrderPaymentWayActivity.class);
                startActivityForResult(intent, CommonConst.OrderConfirmConst.PAYMENT_REQUEST_CODE);
                break;

            // 提交订单
            case R.id.tvOrder:
                if (TextUtils.isEmpty(userAddress.getText())) {
                    ToastUtil.getInstance().show(R.string.order_none_address_not_set);
                } else {
                    //获取经销商最小起送金额
                    getDealersMinAmount();
                }
                break;

            case R.id.rl_getenvelop:
                if (isLoadEnvelopSuc) {
                    // 可用优惠券和不可用优惠券已经获取成功 请求获取平台参数
                    fetchEnvelopParams();  // 丹露红包
                } else {
                    fetchCouponList();
                }
                break;

            default:
                break;
        }
    }

    /**
     * 获取经销商最小起送金额
     */
    private void getDealersMinAmount() {
        DealerMinDeliveryAmtRequest request = new DealerMinDeliveryAmtRequest();
        request.setToken(agent.getToken());
        List<SellerListBean> list = shoppingCartCommitModel.getSellerList();
        List<String> sellerIds = new ArrayList<>();
        for (SellerListBean model : list) {
            String[] strs = model.getSellerId().split("_split_");
            sellerIds.add(strs[0]);
        }
        request.setDealerId(sellerIds);
        agent.getApi()
                .getDealerMinDeliveryAmt(request)
                .compose(OperatorUtils.<DealerMinDeliveryAmtResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<DealerMinDeliveryAmtResponse>(this, R.string.tips_order_submit) {
                    @Override
                    protected void onSuccess(DealerMinDeliveryAmtResponse model) {
                        if (!compareLogic(model.getDealerMinDeliveryAmtModel())) {
                            dismissDialog ();
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 经销商起售金额 需求 比较是否超过经销商最低起售金额
     */
    private boolean compareLogic(List<DealerMinDeliveryAmtResponse.DealerMinDeliveryAmtModelBean> dealerMinDeliveryAmtModel) {
        for (Map.Entry<WrapDealerAttr, BigDecimal> entry : dealersTotalGoodsAmountMap.entrySet()) {
            WrapDealerAttr model = entry.getKey();
            for (DealerMinDeliveryAmtResponse.DealerMinDeliveryAmtModelBean bean : dealerMinDeliveryAmtModel) {
                if (model.getSellerId().equals(bean.getDealerId()) && !TextUtils.isEmpty(bean.getMinDeliveryAmt())) {
                    int compare = CalculatePriceUtil.compare(bean.getMinDeliveryAmt(), entry.getValue().toPlainString());
                    if (compare == 1) {
                        // 未达到经销商起售数量 对话框提示
//                        PromptManager.closeDialog();
                        showNoBeyondMinAmountTipDialog();
                        return false;
                    }
                }
            }
        }
        checkLogic(); //大额红包支付验证
        return true;
    }

    private void showNoBeyondMinAmountTipDialog() {
        new ViewDialog.Builder(this)
                .setTitle("提示")
                .setMessage(getResources().getString(R.string.dealer_min_amount_changed))
                .setCancelable(false)
                .setPositiveButton("点击查看", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).create().show();
    }

    /**
     * 大额红包支付校验
     */
    private void checkLogic() {
        BaseRequest request = new BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi()
                .checkIsSwitch(request)
                .compose(OperatorUtils.<CheckSwitchResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<CheckSwitchResponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(CheckSwitchResponse model) {
                        String bigCouponFlag = model.getBigCouponFlag();
                        if (TextUtils.isEmpty(bigCouponFlag)) {
//                            PromptManager.closeDialog();
                            dismissDialog ();
                            ToastUtil.getInstance().show("未知异常");
                            return;
                        }
                        if (bigCouponFlag.equals("0")) {
                            //不需要开启
                            createOrder(null);  //提交订单
                        } else if (bigCouponFlag.equals("1")) {
                            //需要开启 先判断当前用户是否选择了红包
                            BigDecimal bdTotalUseDiscounAmout = new BigDecimal(0);
                            if (null != selectEnvelops && !selectEnvelops.isEmpty()) {
                                for (CouponListModel couponListModel : selectEnvelops) {
                                    bdTotalUseDiscounAmout = addition(bdTotalUseDiscounAmout.toPlainString(), couponListModel.getCouponAmt());
                                }
                            }
                            // 再加上经销商优惠券+经销商红包 (本身面额)
                            bdTotalUseDiscounAmout = addition(bdTotalUseDiscounAmout.toPlainString(), deductionLogicKeeper.getTotalCouponAmount().toPlainString());
                            bdTotalUseDiscounAmout = CalculatePriceUtil.addition(bdTotalUseDiscounAmout.toPlainString(), deductionLogicKeeper.getTotalDealersEnvelopAmount().toPlainString());

                            int compare = CalculatePriceUtil.compare(bdTotalUseDiscounAmout.toPlainString(), model.getAmount());
                            if (compare == 1 || compare == 0) {
//                                PromptManager.closeDialog();
                                dismissDialog ();
                                showVerifyFragment(model);
                            } else {
                                createOrder(null); //提交订单
                            }
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }

                    @Override
                    public void onCompleted() {
                    }
                });
    }

    @SuppressLint("CommitTransaction")
    protected void showVerifyFragment(CheckSwitchResponse response) {
        validationEnvelopFragment = ValidationEnvelopFragment.newInstance(agent.getLoginUser().getTel(), response.getAmount());
        //        validationEnvelopFragment.setDanluTaskProxy(danluTaskProxy);
        validationEnvelopFragment.setListener(new ICommitListener() {
            @Override
            public void commit(String smsCode) {
                createOrder(smsCode); //提交订单
            }
        });
        validationEnvelopFragment.show(getFragmentManager().beginTransaction(), validationEnvelopFragment.getClass().getSimpleName());
    }

    /**
     * 请求红包获取平台参数（丹露红包）
     */
    private void fetchEnvelopParams() {
        BaseRequest request = new BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi()
                .getEnvelopParam(request)
                .compose(OperatorUtils.<GetCouponParamResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetCouponParamResponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(GetCouponParamResponse model) {
                        payRatio = Float.parseFloat(model.getPayRatio());
                        skipEnvelopableActivity(Integer.parseInt(model.getMaxTicketUseNum()));
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 跳转到 可用和不可用红包界面
     */
    protected void skipEnvelopableActivity(int maxTicketUseNum) {
        Intent intent = new Intent(this, EnvelopeableActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("maxTicketUseNum", maxTicketUseNum);
        bundle.putString("mHighestDeduction", getHightestDeduction());
        bundle.putString("envelop_json", envelopListJsonStr);
        bundle.putSerializable("lastselect", selectEnvelops);
        intent.putExtras(bundle);
        startActivityForResult(intent, USE_ENVELOP_REQ);
    }

    /**
     * 获取最高 （单位是：元）
     */
    private String getHightestDeduction() {
        BigDecimal total = calcHolder.getDanluEnvelopMaxDeduction();
        BigDecimal bd1 = new BigDecimal(payRatio);
        return total.multiply(bd1).toPlainString();// 最高使用优惠券抵扣
    }

    /**
     * 提交订单
     *
     * @param verfyCode
     *         短信验证码
     */
    private void createOrder(String verfyCode) {
        // 提交订单请求对象
        CreateOrderRequest request = new CreateOrderRequest();
        request.setToken(agent.getToken());

        if (!TextUtils.isEmpty(verfyCode)) {
            request.setVerfyCode(verfyCode);
        }
        BigDecimal totalAmt = calcHolder.getAfterDiscountPrice();
        request.setOrderTotalAmt(totalAmt.toPlainString());

        // 构建红包请求参数
        if (null != selectEnvelops && !selectEnvelops.isEmpty()) {
            List<CouponListBean> envelops = new ArrayList<>();
            for (CouponListModel model : selectEnvelops) {
                CouponListBean createModel = new CouponListBean();
                createModel.setCouponCode(model.getCouponCode());
                createModel.setCouponAmt(model.getCouponAmt()); // 红包实际价格
                createModel.setCouponUseAmt(CalculatePriceUtil.intercept(model.getFactUse()));
                envelops.add(createModel);
            }
            request.setCouponList(envelops);
        }
        // 地址参数
        if (selectedAddressModel == null) {
            selectedAddressModel = new DeliverAddressBean();
        }
        request.setDeliverAddress(selectedAddressModel);

        // 发票参数
        if (selectedInvoiceModel == null) {
            selectedInvoiceModel = new InvoiceBean();
            selectedInvoiceModel.setNeedInvoice(CommonConst.InvoiceConst.NEED_INVOICE_NO);
            selectedInvoiceModel.setInvoiceType(null);
            selectedInvoiceModel.setInvoiceId(null);
        }
        request.setInvoice(selectedInvoiceModel);

        // 支付方式参数
        if (TextUtils.isEmpty(paywayValue) || !TextUtils.isDigitsOnly(paywayValue)) {
            paywayValue = CommonConst.PaymentType.PAY_TYPE_ON_LINE;
        }
        request.setPayWay(paywayValue);

        // 请求店铺对象
        List<CreateOrderRequest.SellerListBean> sellerList = null;
        // 店铺数据列表
        List<SellerListBean> storeList = shoppingCartCommitModel.getSellerList();
        for (int i = 0; i < storeList.size(); i++) {
            SellerListBean storeModel = storeList.get(i);
            if (sellerList == null) {
                sellerList = new ArrayList<>();
            }
            CreateOrderRequest.SellerListBean seller = new CreateOrderRequest.SellerListBean();

            String sellerId = storeModel.getSellerId();
            final String splitDealerId = sellerId.substring(0, sellerId.indexOf("_"));
            List<CreateOrderRequest.SellerListBean.MerchListBean> merchList = getMerchList(storeModel.getMerchList(), splitDealerId);
            seller.setComment(storeHolderList.get(i).etBuyerMsg.getText().toString());
            seller.setMerchList(merchList);
            seller.setPaymentFlag(storeModel.getPaymentFlag());
            seller.setSellerId(storeModel.getSellerId());
            seller.setSellerName(storeModel.getSellerName());
            seller.setCodFlag(storeModel.getCodFlag());
            seller.setSupportVatInvoice(storeModel.getSupportVatInvoice());
            seller.setIsYijipayAccount(storeModel.getIsYijipayAccount());
            // 经销商最高支付比
            seller.setDealerPayRatio(deductionLogicKeeper.getDealerPayRatioById(splitDealerId));
            //            why add 构建经销商红包相关
            List<CreateOrderRequest.SellerListBean.DealerCouponListBean> selectDealerEnvelops = deductionLogicKeeper.getHasSelectDealerEnvelopsById(splitDealerId);
            if (null != selectDealerEnvelops && !selectDealerEnvelops.isEmpty()) {
                seller.setDealerCouponList(selectDealerEnvelops); //可选 经销商红包列表(New)
            }
            sellerList.add(seller);
        }
        request.setSellerList(sellerList);

        // 调用提交订单接口
        agent.getApi()
                .createOrderByShoppingCart(request)
                .compose(OperatorUtils.<CreateOrderByShoppingcartNewResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<CreateOrderByShoppingcartNewResponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(CreateOrderByShoppingcartNewResponse model) {
                    }

                    //自行处理，业务状态码较为复杂
                    @Override
                    public void onNext(CreateOrderByShoppingcartNewResponse createOrderResponse) {
                        String validateResult = createOrderResponse.getValidateResult();
                        if (!validateResult.equals("0") || !validateResult.equals(4)) {
//                            PromptManager.closeDialog();
                            dismissDialog ();
                        }
                        switch (validateResult) {
                            case "1":
                                showFragmentTips("验证码错误");
                                break;

                            case "2":
                                //校验码为空
                                showFragmentTips("校验码为空");
                                break;

                            case "3":
                                //其他错误
                                showFragmentTips("未知错误");
                                break;

                            case "5":
                                showFragmentTips("验证码失效");
                                break;

                            default:
                                break;

                        }
                        dismissDialog ();
//                        PromptManager.closeDialog();
                        switch (createOrderResponse.getSuccess()) {
                            case CommonConst.MyOrderDetailConst.ORDER_RESPONSE_SUCCESS_0:
                                // 提交订单成功
                                ToastUtil.getInstance().show(R.string.refer_order_success);
                                // 判断支付方式取不同模型数据
                                List<CreateOrderInfoModelBean.OnlinePaymentModelListBean> onlinePaymentModelsList = createOrderResponse.getCreateOrderInfoModel().getOnlinePaymentModelList();
                                List<CreateOrderInfoModelBean.CashOnDeliveryModelListBean> createOrderCashOnDeliveryModels = createOrderResponse.getCreateOrderInfoModel().getCashOnDeliveryModelList();

                                if (onlinePaymentModelsList != null && onlinePaymentModelsList.size() > 0) {
                                    ArrayList<CreateOrderCashOnDeliveryModels> onlinePaymentArrayList = new ArrayList<>();
                                    for (int i = 0; i < onlinePaymentModelsList.size(); i++) {
                                        CreateOrderCashOnDeliveryModels model = new CreateOrderCashOnDeliveryModels();
                                        model.setPaymentNo(onlinePaymentModelsList.get(i).getPaymentNo());
                                        model.setPrice(onlinePaymentModelsList.get(i).getTotalPrice());
                                        model.setOrderNo(onlinePaymentModelsList.get(i).getOrderNo());
                                        model.setPayType(onlinePaymentModelsList.get(i).getPayType());
                                        onlinePaymentArrayList.add(model);
                                    }
                                    intent.putParcelableArrayListExtra("ONLINE", onlinePaymentArrayList);
                                }
                                if (createOrderCashOnDeliveryModels != null) {
                                    ArrayList<CreateOrderCashOnDeliveryModels> ms = new ArrayList<>();
                                    for (int i = 0; i < createOrderCashOnDeliveryModels.size(); i++) {
                                        CreateOrderCashOnDeliveryModels model = new CreateOrderCashOnDeliveryModels();
                                        model.setOrderNo(createOrderCashOnDeliveryModels.get(i).getOrderNo());
                                        model.setPaymentNo(createOrderCashOnDeliveryModels.get(i).getPaymentNo());
                                        model.setPrice(createOrderCashOnDeliveryModels.get(i).getPrice());
                                        ms.add(model);
                                    }
                                    intent.putParcelableArrayListExtra("CMS", ms);
                                }
                                if (null != validationEnvelopFragment) {
                                    validationEnvelopFragment.dismiss();
                                }
                                intent.setClass(OrderConfirmActivity.this, OrderReferSuccessMultiActivity.class);
                                intent.putExtra("isZero", isZeroOrder);
                                startActivity(intent);
                                OrderConfirmActivity.this.finish();
                                break;

                            case CommonConst.MyOrderDetailConst.ORDER_RESPONSE_SUCCESS_2:
                                CreateOrderResponse.FailedReasonsBean failedReasons = createOrderResponse.getFailedReasons();
                                orderErrorMsg(failedReasons);
                                break;

                            case CommonConst.MyOrderDetailConst.ORDER_RESPONSE_SUCCESS_3:
                                // 提交订单失败
                                ToastUtil.getInstance().show(R.string.refer_order_failed);
                                break;

                            case CommonConst.MyOrderDetailConst.ORDER_RESPONSE_SUCCESS_1:
                                // 重复提单
                                ToastUtil.getInstance().show(R.string.refer_order_check_failed);
                                break;

                            default:
                                // 其他错误
                                ToastUtil.getInstance().show("未知错误");
                                break;
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 商品列表数据模型转换
     */
    private List<CreateOrderRequest.SellerListBean.MerchListBean> getMerchList(List<MerchListBean> goodsList, String sellerId) {
        if (goodsList == null || goodsList.size() < 1) {
            return null;
        }

        List<CreateOrderRequest.SellerListBean.MerchListBean> merchList = null;
        for (MerchListBean goodsModel : goodsList) {
            if (merchList == null) {
                merchList = new ArrayList<>();
            }

            CreateOrderRequest.SellerListBean.MerchListBean merch = new CreateOrderRequest.SellerListBean.MerchListBean();
            merch.setId(goodsModel.getId());
            merch.setMerchBarCode(goodsModel.getMerchBarCode());
            merch.setMerchId(goodsModel.getMerchId());

            // 促销部分
            if (goodsPromotionMap.containsKey(goodsModel.getMerchId())) {
                PromotionModelListBean promotion = goodsPromotionMap.get(goodsModel.getMerchId());

                if ("1".equals(promotion.getIsPromotion())) {
                    merch.setPromotionId(promotion.getPromotionId());
                    merch.setPromotionDetail(promotion.getPromotionInfo());
                    merch.setPromotionType(promotion.getPromotionType());
                    merch.setRuleId(promotion.getRuleId());

                    if (merch.getPromotionType().equals(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4)) {
                        merch.setLimitRuleList(goodsPromotionMap.get(merch.getMerchId()).getLimitRuleList());
                    }

                    merch.setReductionFlg(promotion.getReductionType());
                }
            }
            // why add 构建商品优惠券信息
            DealerBenefitBean benefit = deductionLogicKeeper.getGoodsBenefit(merch.getMerchId(), sellerId);
            merch.setDealerBenefit(benefit);
            merchList.add(merch);
        }

        return merchList;
    }
}
